<?php

/**
 * PathController class
 *
 * @author Julot <andy.julot@gmail.com>
 * @since Thursday, August 11, 2011. 05:01 PM
 */
abstract class PathController extends Controller {
	const TYPE_DOWNLOAD = 'download';
	const TYPE_GALLERY = 'gallery';
	const TYPE_SLIDESHOW = 'slideshow';

	const MODE_DETAIL = 'detail';
	const MODE_THUMBNAIL = 'thumbnail';

	public $type;
	public $mode;

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 *
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow',
				'actions'=>array('index'),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array(
					'upload',
					'addFolder',
					'rename',
					'move',
					'delete',
					'admin',
				),
				'users'=>array('@'),
			),
			array('deny', // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * List all files within path.
	 * @param string $path to folder
	 */
	public function actionIndex($path='') {
		$this->menu = $this->createMenu('index');
		$data = array(
			'type'=>$this->type,
			'label'=>$this->typeName,
			'mode'=>$this->mode,
			'path'=>$path,
		);
		$this->render('application.views.file.index', $data);
	}

	public function actionAdmin($path='') {
		If (!Yii::app()->user->checkAccess($this->type . 'Manage')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->menu = $this->createMenu('admin');

		$data = array(
			'type'=>$this->type,
			'label'=>$this->typeName,
			'path'=>$path,
		);
		$this->render('application.views.file.admin', $data);
	}

	public function getTypeName() {
		switch ($this->type) {
			case self::TYPE_DOWNLOAD:
				return 'Download';
			case self::TYPE_GALLERY:
				return 'Gallery';
			case self::TYPE_SLIDESHOW:
				return 'Slideshow';
			default:
				return 'Unknown';
		}
	}

	public function actionDelete($path, $name) {
		If (!Yii::app()->user->checkAccess($this->type . 'Delete')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		if (Yii::app()->request->isPostRequest) {
			$root = Yii::app()->params['file'];
			if ($path) $absPath = "$root/$this->type/$path/$name";
			else $absPath = "$root/$this->type/$name";
			if (is_file($absPath)) {
				$object = new File($absPath);
			} else {
				$object = new Folder($absPath);
			}
			if (!$object->delete()) {
				$message = "Sorry, $name cannot be deleted. ";
				$message .= 'Please contact your administrator.';
				throw new CHttpException(400, $message);
			} else {
				if (!isset($_GET['ajax'])) {
					if (isset($_POST['returnUrl'])) {
						$returnUrl = $_POST['returnUrl'];
					} else {
						$returnUrl = array('admin');
					}
					$this->redirect($returnUrl);
				}
			}
		} else {
			$message = 'Invalid request. ';
			$message .= 'Please do not repeat this request again.';
			throw new CHttpException(400, $message);
		}
	}

	/**
	 * Upload an image file.
	 *
	 * @param string $path location to save the uploaded file
	 */
	public function actionUpload($path='') {
		If (!Yii::app()->user->checkAccess($this->type . 'Upload')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->menu = $this->createMenu('upload');

		$model = new FileForm("upload-$this->type");
		$root = Yii::app()->params['file'];

		if (isset($_POST['FileForm'])) {
			$model->attributes = $_POST['FileForm'];
			if ($model->validate()) {
				$file = CUploadedFile::getInstance($model, 'file');
				if ($file) {
					if ($model->path) {
						$path = "$root/$this->type/$model->path/$file->name";
					} else {
						$path = "$root/$this->type/$file->name";
					}
					$file->saveAs($path);
					$value = 'File berhasil diupload.';
					Yii::app()->user->setFlash('info', $value);
				} else {
					$error = 'Maaf, file tidak bisa diupload.';
					$model->addError('file', $error);
				}
			}
		}

		$data = array(
			'type'=>$this->type,
			'label'=>$this->typeName,
			'model'=>$model
		);
		$this->render('application.views.file.upload', $data);
	}

	public function actionRename($path, $name) {
		If (!Yii::app()->user->checkAccess($this->type . 'Rename')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->menu = $this->createMenu('rename');

		$model = new FileForm("rename");
		$root = Yii::app()->params['file'];

//		if (isset($_POST['ajax']) && $_POST['ajax'] === 'file-upload-form') {
//			echo CActiveForm::validate($model);
//			Yii::app()->end();
//		}

		if (isset($_POST['FileForm'])) {
			$model->attributes = $_POST['FileForm'];
			if ($path != $model->path || $name != $model->name) {
				if ($model->validate()) {
					if ($path) $absPath = "$root/$this->type/$path/$name";
					else $absPath = "$root/$this->type/$name";
					$object = new Path($absPath);
					if ($model->path) {
						$newAbsPath = "$root/$this->type/$model->path/";
					} else {
						$newAbsPath = "$root/$this->type/";
					}
					$newAbsPath .= $model->name;
					if (file_exists($newAbsPath)) {
						$value = 'Nama sudah ada.';
						Yii::app()->user->setFlash('info', $value);
					} else {
						if ($object->rename($newAbsPath)) {
							if ($path == $model->path) {
								$value = 'Nama berhasil diubah.';
							} else {
								$value = 'Path berhasil dipindah.';
							}
							Yii::app()->user->setFlash('info', $value);
							$url = array('admin', 'path'=>$model->path);
							$this->redirect($url);
						} else {
							$value = 'Nama tidak bisa diubah.';
							Yii::app()->user->setFlash('info', $value);
						}
					}
				}
			} else {
				$this->redirect(array('admin', 'path'=>$path));
			}
		} else {
			$model->name = $name;
			$model->path = $path;
		}

		$data = array(
			'type'=>$this->type,
			'label'=>$this->typeName,
			'model'=>$model,
			'path'=>$path,
			'name'=>$name,
		);
		$this->render('application.views.file.rename', $data);
	}

	public function actionAddFolder() {
		If (!Yii::app()->user->checkAccess($this->type . 'AddFolder')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->menu = $this->createMenu('addFolder');

		$model = new FileForm("add-folder-$this->type");
		$root = Yii::app()->params['file'];

//		if (isset($_POST['ajax']) && $_POST['ajax'] === 'file-upload-form') {
//			echo CActiveForm::validate($model);
//			Yii::app()->end();
//		}

		if (isset($_POST['FileForm'])) {
			$model->attributes = $_POST['FileForm'];
			if ($model->validate()) {
				if ($model->path) {
					$absPath = "$root/$this->type/$model->path";
				}
				else $absPath = "$root/$this->type";
				$folder = new Folder($absPath);
				if (file_exists("$absPath/$model->name")) {
					$value = 'Sub folder sudah ada.';
					Yii::app()->user->setFlash('info', $value);
				} else {
					if ($folder->addFolder($model->name)) {
						$model->name = '';
						$value = 'Sub folder berhasil ditambahkan.';
						Yii::app()->user->setFlash('info', $value);
					} else {
						$value = 'Sub folder tidak bisa ditambahkan.';
						Yii::app()->user->setFlash('info', $value);
					}
				}
			}
		}

		$data = array(
			'type'=>$this->type,
			'label'=>$this->typeName,
			'model'=>$model,
		);
		$this->render('application.views.file.addFolder', $data);
	}

	public function createMenu($current='') {
		$menu = array();
		$user = Yii::app()->user;
		if ($current != 'index') {
			$menu[] = array(
				'label'=>"List $this->typeName",
				'url'=>array('index'),
			);
		}
		if ($current != 'upload') {
			$menu[] = array(
				'label'=>"Upload $this->typeName",
				'url'=>array('upload'),
				'visible'=>$user->checkAccess("{$this->type}Upload"),
			);
		}
		if ($current != 'addFolder') {
			$menu[] = array(
				'label'=>"Add Folder $this->typeName",
				'url'=>array('addFolder'),
				'visible'=>$user->checkAccess("{$this->type}AddFolder"),
			);
		}
		if ($current != 'admin') {
			$menu[] = array(
				'label'=>"Manage $this->typeName",
				'url'=>array('admin'),
				'visible'=>$user->checkAccess("{$this->type}Manage"),
			);
		}
		return $menu;
	}

}

